package com.wawu.server.service;

import com.wawu.common.annotation.IOC.Autowired;
import com.wawu.common.annotation.IOC.component.Service;
import com.wawu.common.constant.JwtClaimsConstant;
import com.wawu.common.constant.MessageConstant;
import com.wawu.common.exception.BaseException;
import com.wawu.common.property.JwtProperties;
import com.wawu.common.utils.JwtUtil;
import com.wawu.pojo.dto.GoodDTO;
import com.wawu.pojo.dto.LoginDTO;
import com.wawu.pojo.entity.*;
import com.wawu.pojo.query.OrderQuery;
import com.wawu.pojo.vo.GetGoodsInfoByGoodsIdVO;
import com.wawu.pojo.vo.GetOrders.GetOrderUserVO;
import com.wawu.pojo.vo.GetOrders.GetOrderVO;
import com.wawu.pojo.vo.LoginVO;
import com.wawu.pojo.vo.UserVO;
import com.wawu.server.dao.*;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理管理员的服务
 */
@Service
public class AdminService {
    @Autowired
    GoodTypesDAO goodTypesDAO;
    @Autowired
    AdminsDAO adminsDAO;
    @Autowired
    UsersDAO usersDAO;
    @Autowired
    GoodsDAO goodsDAO;
    @Autowired
    GoodsDetailsDAO goodsDetailsDAO;
    @Autowired
    OrdersDAO ordersDAO;
    public List<GoodType> getGoodTypes() throws SQLException {
        return goodTypesDAO.getGoodTypes();
    }

    /**
     * 管理员登录
     * （此处数据库中没有加密）
     * @param loginDTO
     * @return
     */
    public LoginVO login(LoginDTO loginDTO) throws SQLException {
        //此处能够顺便校验密码
        List<Admin> admins =adminsDAO.getAdmin(Admin.builder()
                .account(loginDTO.getAccount())
                .pwd(loginDTO.getPwd()).build());
        if(admins ==null|| admins.isEmpty()){
            throw new BaseException(MessageConstant.LOGIN_ACOUNT_NOT_EXIST);
        }
        Admin admin=admins.get(0);
        LoginVO loginVO=new LoginVO();
        loginVO.setName(admin.getName());
        Map<String,Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID,admin.getId());
        loginVO.setToken(JwtUtil.createJWT(JwtProperties.secretKey,JwtProperties.ttl,claims));
        return loginVO;

    }

    //TODO 待优化此处没有判重
    /**
     * 添加商品类型
     * @param typeName
     */
    public void addGoodType(String typeName) throws SQLException {
        goodTypesDAO.insert(typeName);
    }

    /**
     * 获取所有的用户信息
     * @return
     */
    public List<UserVO> getAllUser() throws SQLException, InvocationTargetException, IllegalAccessException {
        List<UserVO> userVOS=new ArrayList<>();
        for(User user:usersDAO.getUsers(new User())){
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(userVO,user);
            userVOS.add(userVO);
        }
        return userVOS;
    }


    //TODO 设置为事务
    /**
     * 添加商品(涉及到商品详情)
     * @param goodDTO
     */
    public void addGood(GoodDTO goodDTO) throws InvocationTargetException, IllegalAccessException, SQLException {
        Good good=new Good();
        BeanUtils.copyProperties(good,goodDTO);
        good.setCreatetime(LocalDateTime.now());
        good.setUpdatetime(LocalDateTime.now());
        good.setId(goodsDAO.insert(good));
        for (GoodDetail goodDetail : goodDTO.getSpecList()) {
            goodDetail.setGoodsId(good.getId());
            goodDetail.setCreateTime(LocalDateTime.now());
            goodDetail.setUpdateTime(LocalDateTime.now());
            goodsDetailsDAO.insert(goodDetail);
        }
    }

    /**
     * 更新商品
     * @param goodDTO
     */
    public void updateGood(GoodDTO goodDTO) throws InvocationTargetException, IllegalAccessException {
        Good good=new Good();
        BeanUtils.copyProperties(good,goodDTO);
        good.setUpdatetime(LocalDateTime.now());
        goodsDAO.update(good);
        for (GoodDetail goodDetail : goodDTO.getSpecList()) {
            goodDetail.setUpdateTime(LocalDateTime.now());
            goodDetail.setCreateTime(null);//这里前端不知道为啥设置了
            goodsDetailsDAO.update(goodDetail);
        }
    }

    /**
     * 通过商品类型删除商品，包括商品详情
     * @param goodId
     */
    public void deleteGoodById(Long goodId) throws SQLException {
        goodsDAO.deleteById(goodId);
        goodsDetailsDAO.deleteByGoodId(goodId);
    }

    /**
     * 获取商品详情
     * @param goodsId
     * @return
     */
    public GetGoodsInfoByGoodsIdVO getGoodsInfoByGoodsId(Long goodsId) throws SQLException {
        List<Good> goods = goodsDAO.getGoods(Good.builder()
                .id(goodsId).build());
        if(goods==null||goods.isEmpty()){
            throw new BaseException(MessageConstant.GOOD_NOT_EXIST);
        }
        Good good=goods.get(0);
        GetGoodsInfoByGoodsIdVO getGoodsInfoByGoodsIdVO=new GetGoodsInfoByGoodsIdVO();
        getGoodsInfoByGoodsIdVO.setGoods(good);
        //获取商品详情（规格）
        List<GoodDetail> goodDetails = goodsDetailsDAO.getGoodDetails(GoodDetail.builder()
                .goodsId(goodsId).build());
        getGoodsInfoByGoodsIdVO.setSpecs(goodDetails);
        return getGoodsInfoByGoodsIdVO;
    }

    /**
     * 添加商品详情
     * @param goodDetail
     * @return
     */
    public GoodDetail addGoodDetail(GoodDetail goodDetail) throws SQLException {
        goodDetail.setCreateTime(LocalDateTime.now());
        goodDetail.setUpdateTime(LocalDateTime.now());
        goodDetail.setId(goodsDetailsDAO.insert(goodDetail));
        return goodDetail;
    }


    //TODO 这里其实有很多业务需要优化但是没时间了，不管了
    /**
     * 条件查询订单
     * @param orderQuery
     * @return
     */
    public List<GetOrderVO> getOrders(OrderQuery orderQuery) throws SQLException, InvocationTargetException, IllegalAccessException {
        List<GetOrderVO> getOrderVOS=new ArrayList<>();
        for (Order order : ordersDAO.getOrders(orderQuery)) {
            GetOrderVO getOrderVO=new GetOrderVO();
            BeanUtils.copyProperties(getOrderVO,order);
            getOrderVO.setTime(order.getUpdateTime());

            //查询用户表
            User user = usersDAO.getUser(User.builder()
                    .id(order.getUserId()).build());
            if (user==null){
                user=new User();
                user.setNickname("已注销用户");
                user.setRecipient("已注销用户");
                user.setAddress("已注销用户");
                user.setPhone("已注销用户");
            }
            GetOrderUserVO getOrderUserVO=new GetOrderUserVO();
            BeanUtils.copyProperties(getOrderUserVO,user);
            getOrderUserVO.setName(user.getRecipient());
            getOrderVO.setUser(getOrderUserVO);


            //查询商品详情表获取规格
            List<GoodDetail> goodDetails = goodsDetailsDAO.getGoodDetails(GoodDetail.builder()
                    .id(order.getGoodsDetailId()).build());
            GoodDetail goodDetail;
            if(goodDetails==null||goodDetails.isEmpty()){
                throw new BaseException(MessageConstant.GOOD_DETAIL_NOT_EXIST);
//                goodDetail=new GoodDetail();
//                goodDetail.setGoodsId();
            }else{
                goodDetail = goodDetails.get(0);
            }

            getOrderVO.setSpec(goodDetail.getSpecName());

            //查询商品表获取商品名字
            Good goodsById = goodsDAO.getGoodsById(goodDetail.getGoodsId());
            getOrderVO.setGoods(goodsById.getName());

            getOrderVOS.add(getOrderVO);
        }
        return getOrderVOS;

    }
}
